package com.ccteam.fluidmusic.view.adapters

import android.content.res.ColorStateList
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.GlobalMediaDataAlbumFootItemBinding
import com.ccteam.fluidmusic.databinding.GlobalMediaDataAlbumHeadItemBinding
import com.ccteam.fluidmusic.databinding.GlobalMediaDataAlbumMusicItemBinding
import com.ccteam.fluidmusic.utils.getColor
import com.ccteam.fluidmusic.view.adapters.viewbinding.MultiTypeViewBindingAdapter
import com.ccteam.fluidmusic.view.bean.*
import com.ccteam.model.music.BITRATE_SQ
import com.ccteam.shared.result.BaseItemData
import com.ccteam.shared.result.album.AlbumDetailFootItem
import com.ccteam.shared.result.album.AlbumDetailHeaderItem
import com.ccteam.shared.result.album.AlbumDetailMusicItem
import com.ccteam.shared.utils.NO_PLAYING
import com.google.android.material.color.MaterialColors

/**
 *
 * @author Xiaoc
 * @since 2021/1/13
 *
 * （全局）专辑页面RecyclerView适配器
 * 专辑页面分为专辑头部（展示专辑内容的）还有其专辑下的各种歌曲内容以及尾部内容
 * 根据不同类型进行不同处理
 */
class GlobalAlbumDetailItemAdapter(
    private val itemClickedCallback: ItemClickedCallback
): MultiTypeViewBindingAdapter(AlbumDetailMusicItem.differCallback) {

    var header: List<AlbumDetailHeaderItem> = emptyList()
    set(value) {
        field = value
        submitList(buildMergedList(newHeader = value))
    }

    var albumMusicList: List<AlbumDetailMusicItem> = emptyList()
    set(value) {
        field = value
        submitList(buildMergedList(newAlbumMusicList = value))
    }

    override fun createMultiViewBinding(
        parent: ViewGroup,
        viewType: Int
    ): RecyclerView.ViewHolder? {
        return when(viewType){
            // 如果是专辑详情头部
            BaseItemData.LAYOUT_ALBUM_DETAIL_HEADER ->{
                GlobalMediaDataAlbumHeadItemBinding.inflate(
                    LayoutInflater.from(parent.context), parent, false)
                AlbumDetailHeaderViewHolder(itemClickedCallback,GlobalMediaDataAlbumHeadItemBinding.inflate(
                    LayoutInflater.from(parent.context), parent, false))
            }
            // 如果是专辑详情的歌曲列表项
            BaseItemData.LAYOUT_ALBUM_DETAIL_MUSIC_ITEM ->{
                AlbumDetailMusicViewHolder(itemClickedCallback,GlobalMediaDataAlbumMusicItemBinding.inflate(
                    LayoutInflater.from(parent.context), parent, false))
            }
            // 如果是专辑详情尾部
            BaseItemData.LAYOUT_ALBUM_DETAIL_FOOT_ITEM ->{
                AlbumDetailFooterViewHolder(GlobalMediaDataAlbumFootItemBinding.inflate(
                    LayoutInflater.from(parent.context), parent, false))
            }
            else ->
                null
        }
    }

    override fun bindMultiItem(
        holder: RecyclerView.ViewHolder,
        position: Int,
        item: BaseItemData,
        payloads: MutableList<Any>,
        viewType: Int
    ) {
        when(viewType){
            // 如果是专辑详情头部
            BaseItemData.LAYOUT_ALBUM_DETAIL_HEADER ->{
                handleAlbumHeader(holder as AlbumDetailHeaderViewHolder,item as AlbumDetailHeaderItem)
            }
            // 如果是专辑详情的歌曲列表项
            BaseItemData.LAYOUT_ALBUM_DETAIL_MUSIC_ITEM ->{
                handleAlbumMusicItem(holder as AlbumDetailMusicViewHolder,item as AlbumDetailMusicItem)
            }
            // 如果是专辑详情尾部
            BaseItemData.LAYOUT_ALBUM_DETAIL_FOOT_ITEM ->{
                handleAlbumFooter(holder as AlbumDetailFooterViewHolder,item as AlbumDetailFootItem)
            }
        }
    }

    private fun handleAlbumHeader(holder: AlbumDetailHeaderViewHolder,item: AlbumDetailHeaderItem){
        holder.item = item

        holder.binding.tvAlbumTitle.text = item.albumTitle
        holder.binding.tvArtist.text = item.artist
        holder.binding.tvSubtitle.text = item.subtitle
        Glide.with(holder.binding.imgAlbumArt)
            .load(item.albumArtUri)
            .placeholder(R.drawable.img_default_album)
            .into(holder.binding.imgAlbumArt)
        if(!item.description.isNullOrEmpty()){
            holder.binding.tvAlbumDescription.visibility = View.VISIBLE
            holder.binding.tvAlbumDescription.text = item.description

            // 判断如果专辑描述文字超过了预设的行数，则开启点击事件可进入详情内容
            with(holder.binding.tvAlbumDescription){
                viewTreeObserver.addOnGlobalLayoutListener {
                    isEnabled = layout?.let {
                        layout.getEllipsisCount(
                            lineCount - 1
                        ) > 0
                    } ?: false
                }
            }
        } else {
            holder.binding.tvAlbumDescription.visibility = View.GONE
        }

    }

    private fun handleAlbumMusicItem(holder: AlbumDetailMusicViewHolder,item: AlbumDetailMusicItem){
        holder.item = item
        holder.binding.tvAlbumMusicTitle.text = item.title
        holder.binding.tvMusicSubtitle.text = item.artist
        holder.binding.tvTrackNum.text = item.numTrack.toString()
        holder.binding.tvBitrate.isVisible = item.bitrate == BITRATE_SQ
        updateActiveItem(holder,item)
    }

    private fun handleAlbumFooter(holder: AlbumDetailFooterViewHolder,item: AlbumDetailFootItem){
        holder.binding.tvFootAlbumInfo.text = holder.itemView.context.getString(R.string.description_album_num_tracks,item.trackNum)
        if(item.year == "0"){
            holder.binding.tvFootAlbumDate.text = holder.itemView.context.getString(R.string.description_album_date,holder.itemView.context.getString(R.string.description_unknown_year))
        } else {
            holder.binding.tvFootAlbumDate.text = holder.itemView.context.getString(R.string.description_album_date,item.year)
        }
        holder.binding.tvFootAlbumCopyright.text = holder.itemView.context.getString(R.string.description_album_copyright,item.copyright)
    }

    private fun updateActiveItem(holder: AlbumDetailMusicViewHolder, item: AlbumDetailMusicItem){
        when(item.playbackRes){
            // 如果没有播放状态的项，则是默认状态
            NO_PLAYING ->{
                holder.binding.root.isEnabled = item.playable
                holder.binding.btnMore.isEnabled = item.playable
                // 如果该项不可播放，则是灰底颜色
                if(item.playable){
                    val colorOnSurface = MaterialColors.getColor(holder.itemView,R.attr.colorOnSurface)
                    val defaultTextColor = holder.itemView.context.getColor(R.color.defaultTextColor)
                    holder.binding.tvAlbumMusicTitle.setTextColor(colorOnSurface)
                    holder.binding.tvMusicSubtitle.setTextColor(defaultTextColor)
                    holder.binding.tvTrackNum.setTextColor(colorOnSurface)
                    holder.binding.btnMore.iconTint = ColorStateList.valueOf(MaterialColors.getColor(holder.binding.tvAlbumMusicTitle, R.attr.colorOnSurface))
                } else {
                    val disableTextColor = holder.itemView.context.getColor(R.color.disableTextColor)
                    holder.binding.tvAlbumMusicTitle.setTextColor(disableTextColor)
                    holder.binding.tvMusicSubtitle.setTextColor(disableTextColor)
                    holder.binding.tvTrackNum.setTextColor(disableTextColor)
                    holder.binding.btnMore.iconTint = ColorStateList.valueOf(holder.binding.tvAlbumMusicTitle.getColor(R.color.disableTextColor))
                }
                holder.binding.ivMusicWave.cancelAnimation()
                holder.binding.ivMusicWave.visibility = View.GONE
            }
            else ->{
                val colorPrimary = MaterialColors.getColor(holder.itemView,R.attr.colorPrimary)
                holder.binding.tvAlbumMusicTitle.setTextColor(colorPrimary)
                holder.binding.tvMusicSubtitle.setTextColor(colorPrimary)
                holder.binding.tvTrackNum.visibility = View.GONE
                holder.binding.ivMusicWave.playAnimation()
                holder.binding.ivMusicWave.visibility = View.VISIBLE
            }

        }
    }

    private fun buildMergedList(
        newHeader: List<AlbumDetailHeaderItem> = header,
        newAlbumMusicList: List<AlbumDetailMusicItem> = albumMusicList
    ): List<BaseItemData>{
        val merged = mutableListOf<BaseItemData>()
        merged.addAll(newHeader)
        merged.addAll(newAlbumMusicList)
        return merged
    }

    inner class AlbumDetailHeaderViewHolder(
        itemClickedCallback: ItemClickedCallback,
        binding: GlobalMediaDataAlbumHeadItemBinding
    ): ViewBindViewHolder<GlobalMediaDataAlbumHeadItemBinding>(binding){
        var item: AlbumDetailHeaderItem? = null

        init {
            binding.btnPlay.setOnClickListener {
                itemClickedCallback.playButtonClicked(it)
            }
            binding.btnShufflePlay.setOnClickListener {
                itemClickedCallback.shufflePlayButtonClicked(it)
            }
            binding.tvAlbumDescription.setOnClickListener {
                item?.let { data ->
                    itemClickedCallback.moreAlbumDescriptionClicked(it,data)
                }
            }
        }

    }

    inner class AlbumDetailMusicViewHolder(
        itemClickedCallback: ItemClickedCallback,
        binding: GlobalMediaDataAlbumMusicItemBinding
    ): ViewBindViewHolder<GlobalMediaDataAlbumMusicItemBinding>(binding){

        var item: AlbumDetailMusicItem? = null

        init {
            binding.root.setOnClickListener { view ->
                item?.let {
                    itemClickedCallback.musicItemClicked(view,it)
                }
            }
            binding.root.setOnLongClickListener { view ->
                item?.let {
                    itemClickedCallback.musicItemMoreClicked(view,it)
                    return@setOnLongClickListener true
                }
                return@setOnLongClickListener false
            }
            binding.btnMore.setOnClickListener { view ->
                item?.let {
                    itemClickedCallback.musicItemMoreClicked(view,it)
                }
            }
        }

    }

    inner class AlbumDetailFooterViewHolder(
        binding: GlobalMediaDataAlbumFootItemBinding
    ): ViewBindViewHolder<GlobalMediaDataAlbumFootItemBinding>(binding)

    interface ItemClickedCallback{
        fun playButtonClicked(view: View)
        fun shufflePlayButtonClicked(view: View)
        fun moreAlbumDescriptionClicked(view: View,description: AlbumDetailHeaderItem)
        fun musicItemClicked(view: View, musicItem: AlbumDetailMusicItem)
        fun musicItemMoreClicked(view: View,musicItem: AlbumDetailMusicItem)
    }

}


